package yygh.hosp.Service.imp;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import yygh.hospital.model.hosp.BookingRule;
import yygh.hospital.model.hosp.Department;
import yygh.hospital.model.hosp.Hospital;
import yygh.hospital.model.hosp.Schedule;
import yygh.hospital.vo.hosp.BookingScheduleRuleVo;
import yygh.hospital.vo.hosp.ScheduleOrderVo;
import yygh.hospital.vo.hosp.ScheduleQueryVo;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import yygh.common.execption.HospitalException;
import yygh.common.result.ResultCodeEnum;
import yygh.hosp.Repository.ScheduleRepository;
import yygh.hosp.Service.DeparmentService;
import yygh.hosp.Service.HospitalService;
import yygh.hosp.Service.ScheduleService;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ScheduleServiceImp implements ScheduleService {
    //mongodb数据库的查询
    @Autowired
    ScheduleRepository scheduleRepository;

    //注入mongodb的mongodbTemplate实现mongodb数据的统计分析
    @Autowired
    MongoTemplate mongoTemplate;

    //注入医院信息的接口
    @Autowired
    HospitalService hospitalService;

    //注入科室信息的接口
    @Autowired
    DeparmentService departmentService;

    //Service层实现排班信息的保存
    @Override
    public void  save(Map<String, Object> map) {
        //首先将传过来的map集合转化成字符串
        String string = JSONObject.toJSONString(map);
        //然后利用json工具类将字符串转换成Hospital对象
        Schedule schedule = JSONObject.parseObject(string, Schedule.class);
        //获取schedule对象的hoscode和hosScheduleId
        String hoscode = schedule.getHoscode();
        String hosScheduleId = schedule.getHosScheduleId();
        //根据传入的schedule对象的hoscode和hosScheduleId判断该Schedule对象是否存在
        Schedule ScheduleExist = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if (ScheduleExist!=null){
            schedule.setUpdateTime(new Date());
            schedule.setStatus(1);
            schedule.setIsDeleted(0);
            scheduleRepository.save(schedule);
        }else {
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setStatus(1);
            schedule.setIsDeleted(0);
            scheduleRepository.save(schedule);
        }
    }

    //Service层实现排班信息的分页查询
    @Override
    public Page<Schedule> findPageSchedule(int page, int limit, ScheduleQueryVo scheduleQueryVo) {
        //首先根据传入的page和limit创建一个Pageable对象
        Pageable pageable=PageRequest.of(page-1,limit);
        //根据传入的departmentQueryVo创建一个schedule对象
        Schedule schedule=new Schedule();
        BeanUtils.copyProperties(scheduleQueryVo,schedule);
        schedule.setIsDeleted(0);
        schedule.setStatus(1);
        //利用mongodb的模糊查询
        ExampleMatcher matcher=ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreCase(true);
        Example<Schedule> example=Example.of(schedule,matcher);
        //调用scheduleRepository的findAll（）方法
        Page<Schedule> schedules = scheduleRepository.findAll(example, pageable);
        return  schedules;
    }

    //Service层实现排班信息的删除
    @Override
    public void remove(String hoscode, String hosScheduleId) {
        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if (schedule!=null){
            scheduleRepository.deleteById(schedule.getId());
        }
    }

    //Service层根据医院编号和对应的科室编号查询具体的排班分页
    @Override
    public Map<String, Object> getRuleSchedule(long page, long limit, String hoscode, String depcode) {
        //1 根据医院编号 和 科室编号 查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);

        //2 根据工作日workDate期进行分组
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),//匹配条件
                Aggregation.group("workDate")//分组字段
                        .first("workDate").as("workDate")
                        //3 统计号源数量
                        .count().as("docCount")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),
                //排序
                Aggregation.sort(Sort.Direction.DESC,"workDate"),
                //4 实现分页
                Aggregation.skip((page-1)*limit),
                Aggregation.limit(limit)
        );
        //调用方法，最终执行
        AggregationResults<BookingScheduleRuleVo> aggResults =
                mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggResults.getMappedResults();

        //分组查询的总记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> totalAggResults =
                mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        int total = totalAggResults.getMappedResults().size();

        //把日期对应星期获取
        for(BookingScheduleRuleVo bookingScheduleRuleVo:bookingScheduleRuleVoList) {
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }

        //设置最终数据，进行返回
        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleRuleList",bookingScheduleRuleVoList);
        result.put("total",total);

        //获取医院名称
        String hosName = hospitalService.getHospName(hoscode);
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname",hosName);
        result.put("baseMap",baseMap);

        return result;
    }

    //Service层：根据医院编号、科室编号和排版日期查询详细的排班信息
    @Override
    public List<Schedule> getScheduleDetail(String hoscode, String depcode, String workDate) {
        List<Schedule> schedules = scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode, depcode, new DateTime(workDate));
        //封装一些具体的参数，如医院名称，科室名称
        schedules.stream().forEach(item->{
            this.packageSchedule(item);
        });
        return schedules;

    }
    //封装一些具体的参数，如医院名称，科室名称
    private void packageSchedule(Schedule item) {
        //对于每一项排版信息，注入相关的信息，如医院名称、科室名称等
        Map<String, Object> param = item.getParam();
        //获取医院名称
        String hospName = hospitalService.getHospName(item.getHoscode());
        //获取科室名称
        String deptName = departmentService.getDepName(item.getHoscode(),item.getDepcode());
        String week = getDayOfWeek(new DateTime(item.getWorkDate()));
        param.put("hospName",hospName);
        param.put("deptName",deptName);
        param.put("week",week);
    }


    /**
     * 根据日期获取周几数据
     * @param dateTime
     * @return
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }

    /**
     *  预约与挂号相关业务逻辑
     */

    //Service层：根据医院编号、科室编号分页查询排班规则
    @Override
    public Map<String, Object> getBookingScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {
        //首先创建最后的结果map集合
        Map<String,Object> result=new HashMap<>();
        //获取预约规则
        //1、根据医院编号获得医院对象，然后得到对应的预约规则
        Hospital hospital = hospitalService.getByHoscode(hoscode);
        if (hospital==null){
            throw  new HospitalException(ResultCodeEnum.DATA_ERROR);
        }
        BookingRule bookingRule = hospital.getBookingRule();

        //2、根据对应的预约规则，获取可预约的所有日期（分页展示），单独方法展示。
       IPage<Date> iPage=this.getListDate(page,limit,bookingRule);
       //3、获取当前可以预约的日期
        List<Date> dateList = iPage.getRecords();

        //4.获取可预约日期里面科室的剩余预约数（查询mongodb信息）
        //满足3个条件，指定医院、科室下工作日期再可预约日期下的条件
            Criteria criteria=Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode)
                    .and("workDate").in(dateList);
        Aggregation agg=Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate").first("workDate").as("workDate")
                .count().as("docCount")
                        .sum("availableNumber").as("availableNumber")
                        .sum("reservedNumber").as("reservedNumber")
        );
        AggregationResults<BookingScheduleRuleVo> aggregate =
                    mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);

        List<BookingScheduleRuleVo> scheduleRuleVoList = aggregate.getMappedResults();

        //5、合并数据，map集合 key日期  value预约规则和剩余数量等
        Map<Date,BookingScheduleRuleVo> scheduleRuleVoMap=new HashMap<>();
        if (!CollectionUtils.isEmpty(scheduleRuleVoMap)){
            scheduleRuleVoMap= scheduleRuleVoList.stream().collect(
                    Collectors.toMap(BookingScheduleRuleVo::getWorkDate, BookingScheduleRuleVo->BookingScheduleRuleVo));
        }

        //6、获取可预约排班规则
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList=new ArrayList<>();
        for (int i = 0,len=dateList.size(); i <len ; i++) {
            Date date = dateList.get(i);
            //从map集合中根据key：日期，得到相关的预约排版规则
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleRuleVoMap.get(date);
            //判断当天是否有排班
            if (bookingScheduleRuleVo==null){
                bookingScheduleRuleVo=new BookingScheduleRuleVo();
                //排班的就诊医生数量为0
                bookingScheduleRuleVo.setDocCount(0);
                //科室剩余的预约数为-1表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            //如果不为空，则封装相应的信息
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            //计算当前预约日期是星期几
            String dayOfWeek = this.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);

            //7、最后一页记录及停号时间设置
            //最后一页最后一条记录为即将预约   状态 0：正常 1：即将放号 -1：当天已停止挂号
            if(i == len-1 && page == iPage.getPages()) {
                bookingScheduleRuleVo.setStatus(1);
            } else {
                bookingScheduleRuleVo.setStatus(0);
            }
            //当天预约如果过了停号时间， 不能预约
            if(i == 0 && page == 1) {
                DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                if(stopTime.isBeforeNow()) {
                    //停止预约
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }

       // 8、封装到最后的结果
        result.put("bookingScheduleRuleVoList",bookingScheduleRuleVoList);
        result.put("total",iPage.getTotal());

        //9.封装其他的相关数据，如医院名称、科室名称、大科室名称、小科室（门诊）名称，放号、停号时间
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospitalService.getHospName(hoscode));
        //科室
        Department department =departmentService.getDepartment(hoscode, depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
            //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        result.put("baseMap", baseMap);

        return  result;
    }




    //根据对应的预约规则，获取可预约的所有日期（分页展示）
    private IPage<Date> getListDate(Integer page, Integer limit, BookingRule bookingRule) {
        //1、获取当天放号时间  年 月 日 小时 分钟预约周期（可预约几天）
     DateTime  relreaseTime= this.getDateTime(new Date(),bookingRule.getReleaseTime());
            //获取可预约的周期,表示最多可以预约几天
            Integer cycle = bookingRule.getCycle();
            //如果当天的放号时间已经过去了，那么预约周期再+1。
            if (relreaseTime.isBeforeNow()){
                cycle=cycle+1;
        }
        //2、获取所有的可预约日期，封装到dateList中
        List<Date> dateList=new ArrayList<>();
        for (int i = 0; i <cycle ; i++) {
            DateTime dateTime = new DateTime().plus(i);
            String dateString = dateTime.toString("yyyy-MM-dd");
            Date date = new DateTime(dateString).toDate();
            dateList.add(date);
        }
        //3、将可预约日期进行分页展示，每页显示日期最多7天数据，超过7天分页
        List<Date> pageDateList=new ArrayList<>();
        int start=(page-1)*limit;
        int end=(page-1)*limit+limit;
        //如果可以显示的日期数量小于7，直接显示
        if (end>dateList.size()){
            end=dateList.size();
        }
        for (int i = start; i <end ; i++) {
            pageDateList.add(dateList.get(i));
        }
        //如果可以显示的日期数量大于7，则进行分页
        IPage<Date> iPage=new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page,7,dateList.size());
        iPage.setRecords(pageDateList);

        return  iPage;
    }


    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " "+ timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }


    //Schedule详细相关预约数据查询
    @Override
    public Schedule getSchedule(String scheduleId) {
        Schedule schedule = scheduleRepository.findById(scheduleId).get();
        this.packageSchedule(schedule);
        return schedule;
    }

    /**
     *  内部接口对应的实现类
     * @param scheduleId
     * @return
     */
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
      ScheduleOrderVo scheduleOrderVo=new ScheduleOrderVo();
        //根据scheduleId获取对应的schedule对象
        Schedule schedule = this.getSchedule(scheduleId);
        //Schedule schedule = baseMapper.selectById(scheduleId);
        if (schedule==null){
            throw  new HospitalException(ResultCodeEnum.DATA_ERROR);
        }
        //根据schedule获取hospital对象
        Hospital hospital = hospitalService.getByHoscode(schedule.getHoscode());
        if (hospital==null){
            throw  new HospitalException(ResultCodeEnum.DATA_ERROR);
        }
        //根据hospital中的预约规则和信息，注入到scheduleOrderVo对象中
        BookingRule bookingRule = hospital.getBookingRule();
        if (bookingRule==null){
            throw  new HospitalException(ResultCodeEnum.DATA_ERROR);
        }
        //注入到scheduleOrderVo中
        scheduleOrderVo.setHoscode(schedule.getHoscode());//编号
        scheduleOrderVo.setHosname(hospitalService.getHospName(schedule.getHoscode()));//名称
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setDepname(departmentService.getDepName(schedule.getHoscode(), schedule.getDepcode()));
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());

        //退号截止天数（如：就诊前一天为-1，当天为0）
        int quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());

        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //预约截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStartTime(startTime.toDate());
        return scheduleOrderVo;

    }
    //Service层实现基于mq的排版信息更新
    @Override
    public void update(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        scheduleRepository.save(schedule);
    }
}
